<template>
  <div>
    <TitleSecondary title="会议记录" />
    <div style="margin-bottom: 20px">
      <ButtonGroup
        v-if="!isEdit"
        :options="clueButtons"
        style="margin-bottom: 20px"
        @click="handleButtonClick"
      />
      <p-table
        class="table-list-container"
        row-key="id"
        :columns="columns"
        :pagination="false"
        bordered
        :custom-row="customRow"
        :data-source="meetRecordData"
        :row-selection="rowSelectionMixin"
        :scroll="{ y: 177 }"
        :loading="load"
        @change="handleTableChange"
      >
        <template slot="email" slot-scope="text, record">
          <a v-if="record.isSendEmail" @click.stop="sendEmail(text, record)">
            <p-icon type="mail" />
          </a>
          <!-- <p-icon type="user" style="margin-right: 8px" /> -->
        </template>
      </p-table>
    </div>
    <DialogSendEmail
      :visible.sync="visible"
      :form="form"
      :visit-id="visitId"
      :customer-code="customerCode"
    />
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import DialogSendEmail from '@/components/dialog/DialogSendEmail.vue';

const defaultForm = {
  subject: '',
  minutesId: '',
  to: [],
  cc: [],
  toValue: [],
};
export default {
  components: {
    DialogSendEmail,
  },

  mixins: [mixinTable],
  props: {
    meetRecordData: {
      type: Array,
      default: () => [],
    },
    meetDetailData: {
      type: Array,
      default: () => [],
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    defaultSelectKey: {
      type: Array,
      default: () => [],
    },
    load: {
      type: Boolean,
      default: false,
    },
    addState: {
      type: Boolean,
      default: false,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    visitId: {
      type: String,
      default: '',
    },
    customerCode: {
      type: String,
      default: '',
    },
  },

  data() {
    const _this = this;
    return {
      rowSelectionMixin: {
        selectedRowKeys: [],
        async onChange(selectedRowKeys, selectedRows) {
          let isSave = false;
          const meetDetailData = JSON.parse(
            JSON.stringify(_this.meetDetailData)
          );
          if (meetDetailData.length) {
            meetDetailData.forEach((item) => {
              if (
                item.id === null ||
                item.id.toString().indexOf('_meet') !== -1
              ) {
                isSave = true;
                return;
              }
            });
          }
          if (isSave) {
            try {
              await _this.$confirm(
                '未保存此操作将丢失新增会议纪要明细的内容，是否确认'
              );
              _this.rowSelectionMixin.selectedRowKeys = selectedRowKeys;
              _this.rowSelectionMixin.selectedRows = selectedRows;
              _this.$emit('select-meet', selectedRowKeys);
            } catch (error) {
              // console.log('error: ', error);
            }
          } else {
            _this.rowSelectionMixin.selectedRowKeys = selectedRowKeys;
            _this.rowSelectionMixin.selectedRows = selectedRows;
            _this.$emit('select-meet', selectedRowKeys);
          }
          _this.$emit('res-date');
        },
      },
      form: {
        ...defaultForm,
      },
    };
  },
  computed: {
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '会议名称',
          dataIndex: 'name',
          width: 300,
        },
        {
          align: 'center',
          title: '创建人',
          dataIndex: 'createUserName',
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
        },
      ];
      if (!this.addState) {
        columns.push({
          align: 'center',
          title: '发送纪要',
          dataIndex: 'email',
          scopedSlots: { customRender: 'email' },
        });
      }
      return columns;
    },
    clueButtons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'meetRecordAdd',
          type: 'primary',
          label: '新增',
          icon: 'plus',
          authKey: '',
        },
        {
          key: 'meetRecordDelete',
          label: '删除',
          icon: 'delete',
          authKey: '',
          disabled,
        },
      ];
    },
  },
  watch: {
    defaultSelectKey: {
      handler(val) {
        if (!val.length) return;
        this.rowSelectionMixin.selectedRowKeys = val;
        this.$emit('select-meet', val);
      },
      immediate: true,
    },
  },
  created() {
    this.rowSelectionMixin.type = 'radio';
  },
  methods: {
    sendEmail(text, record) {
      this.visible = true;
      this.form.subject = record.name;
      this.form.minutesId = record.id;
    },
    customRow(record) {
      return {
        on: {
          click: async (e) => {
            let isSave = false;
            const meetDetailData = JSON.parse(
              JSON.stringify(this.meetDetailData)
            );
            if (meetDetailData.length) {
              meetDetailData.forEach((item) => {
                if (
                  item.id === null ||
                  item.id.toString().indexOf('_meet') !== -1
                ) {
                  isSave = true;
                  return;
                }
              });
            }
            if (isSave) {
              try {
                await this.$confirm(
                  '未保存此操作将丢失新增会议纪要明细的内容，是否确认'
                );
                let keys = record.id;
                this.rowSelectionMixin.selectedRowKeys = [keys];
                this.rowSelectionMixin.selectedRows = [record];
                this.$emit('select-meet', [keys]);
              } catch (error) {
                // console.log('error: ', error);
              }
            } else {
              let keys = record.id;
              this.rowSelectionMixin.selectedRowKeys = [keys];
              this.rowSelectionMixin.selectedRows = [record];
              this.$emit('select-meet', [keys]);
            }
            this.$emit('res-date');
          },
        },
      };
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    handleRow() {},
    async meetRecordAddCallback() {
      let isSave = false;
      if (this.meetDetailData.length) {
        this.meetDetailData.forEach((item) => {
          if (item.id === null || item.id.toString().indexOf('_meet') !== -1) {
            isSave = true;
            return;
          }
        });
      }
      if (isSave) {
        try {
          await this.$confirm(
            '未保存此操作将丢失新增会议纪要明细的内容，是否确认'
          );
          this.$emit('meet-record-add');
        } catch (error) {
          // console.log('error: ', error);
        }
      } else {
        this.$emit('meet-record-add');
      }
    },
    meetRecordDeleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(() => {
          this.$emit('meet-record-delete', ids);
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },
  },
};
</script>
